package com.transaction.service;


import com.transaction.factory.Factory;
import com.transaction.factory.MyFactory;
import com.transaction.repository.MyRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

@Service
public class BusinessService {

    @Autowired
    private MyRepository repository;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private MyFactory myFactory;

    private final ExecutorService executorService = Executors.newFixedThreadPool(2);


    @Transactional(rollbackFor = Exception.class)
    public void doBusiness() {

        // 主线程中的数据库操作
        repository.insertData("主线程插入数据");
        Future<Boolean> future = executorService.submit(() -> transactionTemplate.execute(status -> {
            try {
                repository.insertData("子线程中的数据库操作");
                Factory factory = myFactory.getFactory("factory1");
                factory.insertData("工厂实例写入数据");
                int i = 0/0;
                return true;
            } catch (Exception e) {
                status.setRollbackOnly(); // 子线程回滚
                throw e; // 抛出给主线程感知
            }
        }));

        try {
            future.get();
        } catch (Exception e) {
            throw new RuntimeException("子线程失败，触发主事务回滚", e);
        }
    }
}